<template>
  <div>
    <el-row>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button type="primary" size="mini" @click="huogoods">返回</el-button>
    </el-row>

    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        finish-status="success"
        align-center
        :active="activesize - 0"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs左侧标签页 -->
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormref"
        label-position="top"
      >
        <!-- @tab-click="tabClicked"是tab标签选项被选中时触发的操作 -->
        <!-- :before-leave="deforeTableave" 切换标签之前的钩子，若返回 false则阻止切换。 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activesize"
          :before-leave="deforeTableave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>

            <!-- 级联选择器 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="catelist"
                expand-trigger="hover"
                :props="cateprops"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in manyTabledata"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="it"
                  v-for="(it, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item2.attr_name"
              v-for="item2 in onlyTabledata"
              :key="item2.attr_id"
            >
              <el-input v-model="item2.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action 表示图片上传到的后台接口api地址 -->
            <!-- on-preview是预览图片的操作事件 -->
            <!-- on-remove是处理图片移除的事件 -->
            <!-- 图片上传接收不到请求头的token令牌，手动设置请求头headers -->
            <!-- on-successs上传成功的处理函数 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handeSuccuss"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览的对话框 -->
    <el-dialog title="图片预览" :visible.sync="premadialogVisible" width="50%">
      <img :src="previewPath" alt="" width="100%" />
    </el-dialog>
  </div>
</template>

<script>
import uri from "../../config/uri";
import _ from "lodash";
export default {
  data() {
    return {
      // 设置步骤条当前激活的步骤
      activesize: "0",
      // form 表单的model的数据
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        // 上传成功图片的临时地址
        pics: [],
        // 商品描述
        goods_introduce: "",
        // 动态参数和静态属性
        attrs: [],
      },
      // form表单的验证
      addFormrules: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品价格",
            trigger: "blur",
          },
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: "blur",
          },
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品重量",
            trigger: "blur",
          },
        ],
        goods_cat: [
          {
            required: true,
            message: "请选择商品分类",
            trigger: "blur",
          },
        ],
      },
      // 商品分类列表数据，级联选择器使用
      catelist: [],
      // 级联选择器props配置
      cateprops: {
        // 指定选中的值
        value: "cat_id",
        // 指定看到的值
        label: "cat_name",
        // 父子嵌套的属性
        children: "children",
      },
      //   动态参数的数据
      manyTabledata: [],
      //   静态属性的数据
      onlyTabledata: [],
      //   上传图片的地址
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      //图片上传组件的headers请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 图片预览的图片地址
      previewPath: "",
      // 图片预览的对话框显示与否
      premadialogVisible: false,
    };
  },
  created() {
    this.getcatelist();
  },
  methods: {
    //   获取商品分类列表数据
    async getcatelist() {
      const res = await this.$http.get(uri.getcategories);
      if (res.meta.status === 200) {
        this.catelist = res.data;
      }
    },
    // 级联选择器的事件
    handleChange() {
      if (this.addForm.goods_cat.length === 3) {
        // this.addForm.goods_cat= this.addForm.goods_cat.join(",")
        console.log(this.addForm.goods_cat);
      } else {
        this.addForm.goods_cat = [];
      }
    },
    // 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。
    // 参数1：是要切换的标签数值
    // 参数2：是切换之前的标签页的数值
    deforeTableave(activName, oldActivName) {
      if (oldActivName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    // tab 被选中时触发
    async tabClicked() {
      // 证明访问的是动态参数的面板
      if (this.activesize === "1") {
        const res = await this.$http.get(
          uri.getcategoriesidss + `/${this.cateId}/attributes`,
          { params: { sel: "many" } }
        );
        // console.log(res)
        if (res.meta.status === 200) {
          res.data.forEach((item) => {
            item.attr_vals =
              item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
          });
          this.manyTabledata = res.data;
          console.log(this.manyTabledata);
        } else {
          this, $message.error(res.meta.msg);
        }
      } else if (this.activesize === "2") {
        const res = await this.$http.get(
          uri.getcategoriesidss + `/${this.cateId}/attributes`,
          { params: { sel: "only" } }
        );
        if (res.meta.status === 200) {
          this.onlyTabledata = res.data;
          console.log(this.onlyTabledata);
        }
      }
    },
    // 上传图片的预览事件 file是将要预览的图片信息
    handlePreview(file) {
      this.previewPath = file.response.data.url;
      this.premadialogVisible = true;
    },
    //图片上传，处理图片移除的事件  file是将要被移除的图片信息
    handleRemove(file) {
      // 1，获取将要删除的图片的临时路径
      const filpath = file.response.data.tmp_path;
      // 2，从pics数组中，找到这个图片的对应索引值  使用findIndex新方法，x是数组中的每一项属性
      const i = this.addForm.pics.findIndex((x) => x.pic === filpath);
      // 3，调用数组的splice方法，吧图片信息对象从pics数组中移除
      this.addForm.pics.splice(i, 1);
    },
    // 上传成功的事件处理函数  response是上传成功的对象
    handeSuccuss(response) {
      // 1，拼接得到一个图片的信息对象
      const picsInfo = { pic: response.data.tmp_path };
      // 2，将图片信息对象，push到pics数组中
      this.addForm.pics.push(picsInfo);
      console.log(this.addForm);
    },
    // 提交添加商品的事件
    add() {
      this.$refs.addFormref.validate(async (valid) => {
        if (valid) {
          // 需要深拷贝一个新的addForm对象 安装lodash包，使用其中的cloneDeep用来深拷贝
          //    const form= _.cloneDeep(this.addForm)
          const form = JSON.parse(JSON.stringify(this.addForm));
          form.goods_cat = form.goods_cat.join(",");
          //    需要处理动态参数和静态属性
          // 动态参数
          this.manyTabledata.forEach((item) => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(" "),
            };
            this.addForm.attrs.push(newInfo);
          });
          // 静态属性
          this.onlyTabledata.forEach((item) => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals,
            };
            this.addForm.attrs.push(newInfo);
          });
          form.attrs = this.addForm.attrs;
          console.log(form);
          //   发起请求
          const res = await this.$http.post(uri.postgoods, form);
          console.log(res);
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg);
            this.$router.push("/goods");
          } else {
            this.$message.error(res.meta.msg);
          }
        } else {
          return this.$message.error("请填写必要的表单项");
        }
      });
    },
    huogoods(){
        this.$router.push("/goods")
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 10px 0;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.el-button {
  margin-top: 10px;
}
.el-row{
    width: 100%;
    
    .el-breadcrumb{
        float: left;
    }
    .el-button{
        margin-bottom: 10px;
        float: right;
        
    }
}
</style>
